<template>
  <div class="login-container">
    <div class="login-box">
      <div style="font-weight: bold; font-size: 24px; text-align: center; margin-bottom: 30px; color: #1450aa">欢 迎 注 册</div>
      <el-form ref="formRef" :model="data.form" :rules="data.rules">
        <div style="text-align: center; margin-bottom: 20px">
          <el-upload
              :action="baseUrl + '/files/upload'"
              :on-success="handleFileUpload"
              :show-file-list="false"
              class="avatar-uploader"
          >
            <img v-if="data.form.avatar" :src="data.form.avatar" class="avatar"  alt="头像"/>
            <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </div>
        <el-form-item prop="username">
          <el-input :prefix-icon="User" size="large" v-model="data.form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input show-password :prefix-icon="Lock" size="large" v-model="data.form.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input show-password :prefix-icon="Lock" size="large" v-model="data.form.confirmPassword" placeholder="请确认密码"></el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input v-model="data.form.phone" :prefix-icon="Iphone" size="large" placeholder="请输入电话"></el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input v-model="data.form.email" :prefix-icon="Message" size="large" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item prop="role">
          <el-select size="large" placeholder="请选择角色" v-model="data.form.role">
            <template #prefix>
              <el-icon><UserFilled /></el-icon>
            </template>
            <el-option label="访客" value="USER"></el-option>
            <el-option label="管理员" value="ADMIN"></el-option>
            <el-option label="读者" value="READER"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="large" type="primary" style="width: 100%" @click="register">注 册</el-button>
        </el-form-item>
        <div style="text-align: right">
          已有账号？请 <a href="/login">登录</a>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { User, Lock, Iphone, Message, UserFilled } from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";

const baseUrl = import.meta.env.VITE_BASE_URL

//验证密码
const validatePass = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请确认密码'))
  } else {
    if (value !== data.form.password) {
      callback(new Error("确认密码跟原密码不一致!"))
    }
    callback()
  }
}

//验证手机号码
const validatePhone = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请输入电话号码'));
  }
  const phoneRegex = /^1[3-9]\d{9}$/; // 中国大陆手机号
  if (!phoneRegex.test(value)) {
    callback(new Error('请输入正确的手机号码'));
  } else {
    callback();
  }
};

// 自定义邮箱验证规则
const validateEmail = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请输入邮箱地址'));
  }
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (!emailRegex.test(value)) {
    callback(new Error('请输入正确的邮箱格式'));
  } else {
    callback();
  }
};

//密码强度检测
const validatePassword = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请输入密码'))
  }

  const checks = {
    length: value.length >= 8,
    hasNumber: /\d/.test(value),
    hasLetter: /[a-zA-Z]/.test(value),
    hasSpecial: /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(value)
  }

  const errors = []

  if (!checks.length) errors.push('至少8个字符')
  if (!checks.hasNumber) errors.push('包含数字')
  if (!checks.hasLetter) errors.push('包含字母')
  if (!checks.hasSpecial) errors.push('包含特殊字符')

  if (errors.length > 0) {
    return callback(new Error(`密码必须满足：${errors.join('、')}`))
  }

  callback()
}

const data = reactive({
  form: { },
  user: {},
  rules: {
    username: [
      { required: true, message: '请输入账号', trigger: 'blur' }
    ],
    password: [
      { required: true, validator: validatePassword, message: '密码长度须大于8位且包含数字、字母、特殊字符', trigger: 'blur' }
    ],
    confirmPassword: [
      { validator: validatePass, trigger: 'blur' }
    ],
    phone: [
      { validator: validatePhone, trigger: 'blur' }
    ],
    email: [
      { validator: validateEmail, trigger: 'blur' }
    ],
    role: [
      { required: true, message: '请选择角色', trigger: 'blur' }
    ]
  }
})

const formRef = ref()

const register = () => {
  formRef.value.validate(valid => {
    if (valid) { // 表示表单校验通过
      console.log('form: ', data.form)
      request.post('/register', data.form).then(resp => {
        if (resp.code === '200') {
          console.log(resp)
          ElMessage.success(resp.msg)
          setTimeout(() => {
            router.push('/login')
          }, 3000)
        } else {
          ElMessage.error(resp.msg)
        }
      })
    }
  })
}

const handleFileUpload = (res) => {
  data.form.avatar = res.data
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(to top, #00467f, #a5cc82);
}
.login-box {
  width: 350px;
  padding: 30px;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  background-color: rgba(255, 255, 255, 0.5);
}
.avatar-uploader {
  height: 120px;
}
.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
</style>